package farmer.update.unit;

import farmer.render.building.City;

import pathfinding.grid.GridPath;

import farmer.update.building.LumberCamp;
import farmer.update.building.Map;
import farmer.update.building.Windmill;
import farmer.update.building.Mine;

import farmer.core.Building;
import farmer.core.BuildingRessource;
import farmer.core.Unit;

public abstract class Transporter extends Unit{
	
	private Building base;
	private BuildingRessource destination;
	
	protected int wood = 0;
	protected int food = 0;
	protected int rock = 0;
	
	private boolean isReturningToBase = false;

	public Transporter(int x, int y, Building base) {
		super(x, y);
		this.base = base;
	}
	
	public void addRessource(int food, int wood, int rock){
		this.food += food;
		this.wood += wood;
		this.rock += rock;
	}
	
	public void resetRessource(){
		food = 0;
		wood = 0;
		rock = 0;
	}
	
	public void setBuilding(BuildingRessource building){
		destination = building;
	}
	
	public BuildingRessource getBuilding(){
		return destination;
	}
	
	public int getWood(){
		return wood;
	}
	
	public int getFood(){
		return food;
	}
	
	public int getRock(){
		return rock;
	}
	
	public void update(int deltaTime){
		super.update(deltaTime);
		//Try to reach destination
		if(destination != null){
			int x = (int) (posX/Map.cellWidth);
			int y = (int) (posY/Map.cellWidth);
			if(x == destination.getX()+1 && y == destination.getY()+2){
				isReturningToBase = true;
				if(destination instanceof LumberCamp){
					wood += destination.getRessource();
				}else if(destination instanceof Windmill){
					food += destination.getRessource();
				}else if(destination instanceof Mine){
					rock += destination.getRessource();
				}
				GridPath path = map.getPath(this, base);
				setPath(path);
				City city = (City)base;
				city.isReturningToBase((farmer.render.unit.Transporter) this);
				destination = null;
			}
		}
		//Return to base
		if(isReturningToBase){
			int x = (int) (posX/Map.cellWidth);
			int y = (int) (posY/Map.cellWidth);
			if(x == base.getX()+2 && y == base.getY()+2){
				isReturningToBase = false;
				if(base instanceof City){
					City city = (City)base;
					city.addFreeTransporter((farmer.render.unit.Transporter) this);
				}
			}
		}
	}

}
